| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- import { isEmpty, pick } from "lodash";
- import { NextResponse } from "next/server";
- import { WLEDClient } from "wled-client";
- import config from "data/config.json";
- const action = async ({ client, on }) => {
- let wled;
- let errors = [];
- try {
- console.log("connect to", client);
- wled = new WLEDClient(client); // setup a connection to the client
- await wled.init(); // init the connection
- } catch (err) {
- errors.push({ error: err.message, type: "connect", client });
- }
- try {
- console.log("set power to", on);
- if (on) await wled.turnOn(); // turn off the lights
- else await wled.turnOff(); // turn off the lights
- } catch (err) {
- errors.push({ error: err.message, type: "power", client, on });
- }
- try {
- await wled.refreshState();
- } catch (err) {
- console.log("state refresh", err.message);
- errors.push({ error: err.message, type: "refreshState", client });
- }
- return { ...pick(wled?.state || {}, ["on"]), errors };
- };
- export async function GET(req, { params }) {
- let id = params?.id;
- let promises = [];
- try {
- if (!id) throw new Error("Invalid power state");
- let clients = (config && Object.keys(config)) || [];
- if (isEmpty(clients)) throw new Error("No clients found");
- for (let client of clients) {
- promises.push(action({ client, on: id === "on" || false }));
- }
- } catch (err) {
- return NextResponse.json({ error: err?.message }, { status: 500 });
- }
- return Promise.allSettled(promises)
- .then((results) => {
- console.log("results", results);
- return NextResponse.json(results?.map((o) => o?.value));
- })
- .catch((err) => {
- return NextResponse.json({ error: err?.message }, { status: 500 });
- });
- }
|